//
//  UIScrollView+Scale.m
//  Tool
//
//  Created by Mr.Zhang on 2018/9/3.
//  Copyright © 2018年 Starunion. All rights reserved.
//

#import "UIScrollView+Scale.h"
#import <objc/runtime.h>

@implementation UIScrollView (Scale)

@dynamic scaleHeader;
@dynamic minScaledHeight;

- (void)setScaleHeader:(UIView *)scaleHeader{
    
    if (self.scaleHeader == scaleHeader) return;
    
    UIView *scale = self.scaleHeader;
    
    if (scale) [scale removeFromSuperview];
    
    if (scaleHeader){
        [self addSubview:scaleHeader];
        
        UIEdgeInsets insets = self.contentInset;
        
        CGRect frame = scaleHeader.frame;
        frame.origin.x = 0;
        frame.origin.y = - CGRectGetHeight(frame) - insets.top;
        scaleHeader.frame = frame;
        
        
        insets.top += CGRectGetHeight(frame);
        
        self.contentInset = insets;
        CGSize size = self.contentSize;
        size.height += CGRectGetHeight(frame);
        
        self.contentSize = size;
    }else{
        if (scale){
            
            UIEdgeInsets insets = self.contentInset;
            
            CGRect frame = scale.frame;
            insets.top -= CGRectGetHeight(frame);
            
            self.contentInset = insets;
            CGSize size = self.contentSize;
            size.height -= CGRectGetHeight(frame);
            
            self.contentSize = size;
            
        }
    }
    
    objc_setAssociatedObject(self, "scaleHeader", scaleHeader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)scaleHeader{
    return objc_getAssociatedObject(self, "scaleHeader");
}

- (void)setMinScaledHeight:(CGFloat)minScaledHeight{
    objc_setAssociatedObject(self, "minScaledHeight", @(minScaledHeight), OBJC_ASSOCIATION_COPY);
}

- (CGFloat)minScaledHeight{
    return [objc_getAssociatedObject(self, "minScaledHeight") floatValue];
}

- (void)setContentOriginInsets:(UIEdgeInsets)contentOriginInsets{
    objc_setAssociatedObject(self, "contentOriginInsets", [NSValue valueWithUIEdgeInsets:contentOriginInsets], OBJC_ASSOCIATION_COPY);
}
- (UIEdgeInsets)contentOriginInsets{
    return [objc_getAssociatedObject(self, "contentOriginInsets") UIEdgeInsetsValue];
}

- (void)scaleHeaderWithChange:(CGFloat)toHeight{
    CGFloat off = CGRectGetHeight(self.scaleHeader.bounds) - toHeight;
    UIEdgeInsets insets = self.contentInset;
    insets.top -= off;
    self.contentInset = insets;
    
    CGRect frame = self.scaleHeader.frame;
    frame.origin.x = 0;
    frame.origin.y = - insets.top;
    frame.size.height = toHeight;
    
    self.scaleHeader.frame = frame;
}

@end
